package com.example.demo.util;

import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;

/**
 * openpdf生成pdf
 */
public class OpenPdfUtil {

    Document document = new Document();// 建立一个Document对象
    PdfWriter pdfWriter;

    //标题
    private static Font titlefont;
    //时间
    private static Font timefont;
    //内容
    private static Font textfont;

    static{
        BaseFont bfChinese;
        try {
            bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);

            titlefont = new Font(bfChinese, 20, Font.BOLD);// 设置字体大小
            timefont = new Font(bfChinese, 14, Font.NORMAL);// 设置字体大小
            textfont = new Font(bfChinese, 10, Font.NORMAL);// 设置字体大小
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public OpenPdfUtil(File file) {

        document.setPageSize(PageSize.A4);// 设置页面大小
        try {
            pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(file));
            // 定义页眉和页脚页码事件，PDFBuilder代码在后面
            OpenPdfPageEventHelper helper = new OpenPdfPageEventHelper();
            pdfWriter.setPageEvent(helper);
            document.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public PdfPCell createCell(String value,com.lowagie.text.Font font,int align){

        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value,font));
        return cell;

    }

    public PdfPCell createCell(String value,com.lowagie.text.Font font,int align,int colspan, int rowspan){

        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value,font));
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        return cell;

    }
    public PdfPCell createCell(Phrase phrase ,com.lowagie.text.Font font,int align,int colspan, int rowspan){

        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(phrase);
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        return cell;

    }



    public PdfPCell createCell(String value,com.lowagie.text.Font font){

        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPhrase(new Phrase(value,font));
        return cell;

    }



    public PdfPCell createCell(String value,com.lowagie.text.Font font,int align,int colspan,boolean boderFlag){

        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value,font));
        cell.setPadding(3.0f);
        if(!boderFlag){
            cell.setBorder(0);
            cell.setPaddingTop(15.0f);
            cell.setPaddingBottom(8.0f);
        }

        return cell;
    }

    public PdfPTable createTable(int colNumber){

        PdfPTable table = new PdfPTable(colNumber);
        try{
            table.setTotalWidth(new float[]{44,97,112,45,72,54,55});
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        }catch(Exception e){
            e.printStackTrace();
        }

        return table;

    }



    /**
     * 绘制标题
     *
     * @param font
     * @param titleName
     * @return
     */
    public static Paragraph setParagraph(Font font, String titleName) {
        Paragraph paragraph = new Paragraph(titleName, font);
        //设置文字居中
        paragraph.setAlignment(Element.ALIGN_CENTER);
        //行间距
        paragraph.setLeading(5f);
        //设置段落上空白
        paragraph.setSpacingBefore(-20f);
        //设置段落下空白
        paragraph.setSpacingAfter(15f);
        return paragraph;
    }

    /**
     * 获取字体大小（超过长度则缩小字体）
     * @param baseFont
     * @param value
     * @return
     */
    private static Font getFont(BaseFont baseFont, String value) {
        int textBoxWidth = 45;
        int fontSize = 10;
        float textWidth = baseFont.getWidthPoint(value, fontSize);
        // 文本框高度只够写一行，并且文字宽度大于文本框宽度，则缩小字体
        while (textWidth > textBoxWidth) {
            fontSize--;
            textWidth = baseFont.getWidthPoint(value, fontSize);
        }
        return new Font(baseFont, fontSize, Font.NORMAL);
    }

    public int createCell(PdfPTable table, String content,BaseFont baseFont,int maxWidth) {
        Phrase phrase = new Phrase("", textfont);
        int lineIndex = 0;
        int lineNum = 0;
        while (StringUtils.isNotEmpty(content)) {
            lineIndex = getLineIndex(content, baseFont, maxWidth);
            phrase.add(content.substring(0, lineIndex) + "\r\n");
            content = content.substring(lineIndex);
            lineNum ++;
        }
        PdfPCell cell = createCell(phrase, textfont, Element.ALIGN_LEFT, 1, 1);
        table.addCell(cell);
        return lineNum;
    }

    /**
     * 获取截取位置 --该方法升级JDK1.8需要做修改
     * @param content 内容
     * @param baseFont 字体计算器
     * @param maxWidth 最大宽度
     * @return 截取位置
     */
    public int getLineIndex(String content, BaseFont baseFont, int maxWidth) {
        int fontSize = 10;
        String [] strings = content.split("");
        float remainder = 0;
        int index = 0;
        for (; index < strings.length; index++) {
            remainder = remainder + baseFont.getWidthPoint(strings[index], fontSize);
            if (remainder > maxWidth) {
                break;
            }
        }
        return index;
    }

    /**
     * 生成页码
     *
     * @param pdfWriter
     * @param document
     */
    public static void addPageNum(PdfWriter pdfWriter, Document document) {
        try {
            //创建一个两列的表格
            PdfPTable table = new PdfPTable(1);
            table.setTotalWidth(20);
            //锁定列宽
            table.setLockedWidth(true);
            //设置每列宽度
            table.setWidths(new int[]{20});
            // 设置页码，字体大小为12号，灰色
            PdfPCell cell = new PdfPCell(new Phrase("—  " + document.getPageNumber() + "  —", textfont));

            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.disableBorderSide(-1);
            table.addCell(cell);

            // 将页码写到距离pdf底部30px的位置
            table.writeSelectedRows(0, -1, 0, 30, pdfWriter.getDirectContent());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("设置页脚失败！");
        }
    }


    public void generatePDF() throws Exception{

        Paragraph paragraph = setParagraph(titlefont, "红字发票信息确认单");
        document.add(paragraph);

        PdfPTable table = createTable(7);

        table.addCell(createCell("填开日期：2024年03月01日", timefont,Element.ALIGN_LEFT,7,false));

        table.addCell(createCell("销售方", textfont, Element.ALIGN_CENTER, 1, 2));
        table.addCell(createCell("纳税人名称（销方）", textfont, Element.ALIGN_CENTER));
        table.addCell(createCell("测试测试企业名称", textfont, Element.ALIGN_CENTER));
        table.addCell(createCell("购买方", textfont, Element.ALIGN_CENTER,1,2));
        table.addCell(createCell("纳税人名称（购方）", textfont, Element.ALIGN_CENTER));
        table.addCell(createCell("测试购方企业名称", textfont, Element.ALIGN_CENTER,2,1));

        table.addCell(createCell("统一社会信用代码/纳税人识别号（销方）", textfont, Element.ALIGN_CENTER));
        table.addCell(createCell("91440604MA52J0J10H", textfont, Element.ALIGN_CENTER));
        table.addCell(createCell("统一社会信用代码/纳税人识别号（购方）", textfont, Element.ALIGN_CENTER));
        table.addCell(createCell("911136587421536541", textfont, Element.ALIGN_CENTER,2,1));

        int num = 89;
        table.addCell(createCell("开具\r\n红字\r\n发票\r\n确认\r\n信息\r\n内容", textfont, Element.ALIGN_CENTER,1,num+3));
        table.addCell(createCell("项目名称", textfont, Element.ALIGN_CENTER));
        table.addCell(createCell("数量", textfont, Element.ALIGN_CENTER));
        table.addCell(createCell("单价", textfont, Element.ALIGN_CENTER));
        table.addCell(createCell("金额", textfont, Element.ALIGN_CENTER));
        table.addCell(createCell("税率/征收率", textfont, Element.ALIGN_CENTER));
        table.addCell(createCell("税额", textfont, Element.ALIGN_CENTER));

        //明细
        BaseFont baseFont = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
        int lineNum = 0;
        int current = 1;
        for(int i=1;i<=num;i++){
            String conent = "*蔬菜*豆芽235621624嗯我绕所64375327"+i;
            lineNum = lineNum + createCell(table, conent, baseFont, 95);
            table.addCell(createCell(i+"", textfont));
            String str = "1.21111111123467";
            Font font = getFont(baseFont, str);
            table.addCell(createCell(str, font));
            table.addCell(createCell("1.2", textfont));
            table.addCell(createCell("0%", textfont));
            table.addCell(createCell("0.00", textfont));
            if (lineNum >50 && current == 1) {
                lineNum = 0;
                current ++;
                document.add(table);
                table = createTable(7);
                table.addCell(createCell("开具\r\n红字\r\n发票\r\n确认\r\n信息\r\n内容", textfont, Element.ALIGN_CENTER,1,num-i+1));
            } else if (lineNum >62 && current > 1) {
                lineNum = 0;
                current ++;
                document.add(table);
                table = createTable(7);
                table.addCell(createCell("开具\r\n红字\r\n发票\r\n确认\r\n信息\r\n内容", textfont, Element.ALIGN_CENTER,1,num-i+2));
            }
        }
        table.addCell(createCell("合计", textfont));
        table.addCell(createCell("----", textfont));
        table.addCell(createCell("----", textfont));
        table.addCell(createCell("6.00", textfont));
        table.addCell(createCell("----", textfont));
        table.addCell(createCell("6.00", textfont));
        lineNum ++;
        if (lineNum >50 && current == 1) {
            document.add(table);
            table = createTable(7);
            table.addCell(createCell("开具\r\n红字\r\n发票\r\n确认\r\n信息\r\n内容", textfont, Element.ALIGN_CENTER,1,1));
        } else if (lineNum >62 && current > 1) {
            document.add(table);
            table = createTable(7);
            table.addCell(createCell("开具\r\n红字\r\n发票\r\n确认\r\n信息\r\n内容", textfont, Element.ALIGN_CENTER,1,1));
        }

        Phrase phrase = new Phrase("", textfont);
        phrase.add("一、录入方身份：\r\n");
        phrase.add("    1.销售方□☑ 2.购买方□☑ \r\n");
        phrase.add("二、冲红原因：\r\n");
        phrase.add("    1.开票有误□☑  2.销货退回□☑  3.服务终止□☑  4.销售折让□☑ \r\n");
        phrase.add("三、对应蓝字发票抵扣增值税销项税额情况：\r\n");
        phrase.add("    1.已抵扣□☑  2.未抵扣□☑ \r\n");
        phrase.add("对应蓝字发票的代码： 号码： 24442000000000071607\r\n");
        phrase.add("四、是否涉及数量（仅限成品油、机动车等业务填写）\r\n");
        phrase.add("    涉及销售数量□☑  仅涉及销售金额□☑ \r\n");
        PdfPCell cell = createCell(phrase, textfont, Element.ALIGN_LEFT, 6, 1);
        table.addCell(cell);

        table.addCell(createCell("红字发票\r\n信息确认\r\n单编号", textfont, Element.ALIGN_CENTER));
        table.addCell(createCell("\r\n\r\n\r\n\r\n24442000000000071607\r\n\r\n\r\n\r\n\r\n", textfont, Element.ALIGN_LEFT,6,1));

        document.add(table);
        document.close();

    }


    public static void main(String[] args) throws Exception {

        File file = new File("D:\\text.pdf");
        file.createNewFile();
        new OpenPdfUtil(file).generatePDF();

    }

}